package com.veo.dao.Impl;

import com.veo.dao.BookDao;
import com.veo.entity.Books;
import com.veo.entity.BorrowBooks;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.ejb.TimerHandle;
import javax.xml.transform.Transformer;
import java.util.List;

@Repository("bookDao")
public class BookDaoImpl extends HibernateDaoSupport implements BookDao {

    @Resource(name = "sessionFactory")
    public void setSessionFactory1(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }


    @Override
    public List<Books> getAllBooksToTable() {
        List<Books> books = (List<Books>) this.getHibernateTemplate().loadAll(Books.class);
        return books;
    }

    @Override
    public List<BorrowBooks> getUserBorrowBooks(String id) {
        SessionFactory sessionFactory = this.getSessionFactory();
        Session session = sessionFactory.getCurrentSession();
        String sql="select isbn,books.bookName,author,type,press,idCard,user.username,borrowTime from borrowBooks,books,user\n" +
                "                where books.id=borrowBooks.bookId and user.id=borrowBooks.userId and user.id="+id;
        List list = session.createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(BorrowBooks.class)).list();
        System.out.println(list.size());
        System.out.println(list.get(1));
        return list;
    }

    @Override
    public void deleteBooks(Books books) {
        this.getHibernateTemplate().delete(books);
    }

    @Override
    public void addBook(Books books) {
        this.getHibernateTemplate().save(books);
        this.getHibernateTemplate().flush();
    }

    @Override
    public void updateBook(Books books) {
        this.getHibernateTemplate().update(books);
        this.getHibernateTemplate().flush();
    }
}
